package cn.anecansaitin.industrialization_expansion.client.event;

import cn.anecansaitin.industrialization_expansion.ExtensionLoader;
import cn.anecansaitin.industrialization_expansion.ModConstant;
import cn.anecansaitin.industrialization_expansion.api.common.item.IToolModule;
import cn.anecansaitin.industrialization_expansion.client.item.BakedModel.ModifiedToolModel;
import cn.anecansaitin.industrialization_expansion.client.model.ExtendedModel;
import cn.anecansaitin.industrialization_expansion.common.item.ItemRegister;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.client.renderer.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Mod.EventBusSubscriber(modid = ModConstant.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public class OnModelBaked {
    /**
     * 为物品设置对应的模型 <br/>
     * 因为是通过读取外部文件进行注册，物品没有对应的模型，需要在模型烘焙前把对应的模型放进去。
     */
    @SubscribeEvent
    public static void setModel(ModelBakeEvent event) {
        setModifiedToolModel(event);
        setModuleItemModel(event);
    }

    /**
     * 设置工具的模型
     */
    private static void setModifiedToolModel(ModelBakeEvent event) {
        Map<ResourceLocation, IBakedModel> modelRegistry = event.getModelRegistry();
        ModelResourceLocation pickaxeLocation = new ModelResourceLocation(Objects.requireNonNull(Items.DIAMOND_PICKAXE.getRegistryName()), "inventory");
        ArrayList<Item> items = new ArrayList<>(ExtensionLoader.TOOLS);
        items.add(ItemRegister.TOOL.get());
        items.forEach(item -> {
            ModelResourceLocation location = getLocation(item.getRegistryName());
            IBakedModel model = modelRegistry.get(location);

            if (model instanceof ModifiedToolModel)
                return;

            modelRegistry.put(location, new ModifiedToolModel(modelRegistry.get(pickaxeLocation)));
        });
    }

    /**
     * 设置各个模块物品的模型
     */
    private static void setModuleItemModel(ModelBakeEvent event) {
        Map<ResourceLocation, IBakedModel> modelRegistry = event.getModelRegistry();
        List<Item> modules = ExtensionLoader.MODULES;
        modules.forEach(item -> modelRegistry.put(getLocation(item.getRegistryName()), ExtendedModel.get(((IToolModule) item).getIcon())));
    }

    private static ModelResourceLocation getLocation(String path) {
        return new ModelResourceLocation(path, "inventory");
    }

    private static ModelResourceLocation getLocation(ResourceLocation path) {
        return new ModelResourceLocation(path, "inventory");
    }
}
